import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
// 以下代码为了不需要去单独引入./modules下的路由模块
// otherRouters会自动放入所有./modules下的路由模块
const modulesFiles = require.context('./modules', true, /\.js$/);
let otherRouters = [];
modulesFiles.keys().reduce((modules, modulePath) => {
  const value = modulesFiles(modulePath);
  otherRouters.push(...value.default);
}, {});

const routes = [
  ...otherRouters,
  {
    path: '/404',
    name: '404',
    meta: {
      title: '404'
    },
    component: () =>
      import(
        /* webpackChunkName: "404" */
        '@/views/404.vue'
      )
  },
  {
    // 所有匹配不到的路由都重定向到404
    path: '*',
    redirect: '/404'
  }
];

const router = new VueRouter({
  mode: 'history',
  routes
});
router.beforeEach((to, from, next) => {
  // set page title
  document.title = to.meta.title;
  next();
});
export default router;
